package com.siyoumi.app.rabbitmq;

import com.siyoumi.component.XSpringContext;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class RabbitMqConfig {
    @Bean
    @ConfigurationProperties("rabbitmq")
    public RabbitMqProperties rabbitMqProperties() {
        return new RabbitMqProperties();
    }

    @SneakyThrows
    @Bean(name = "rabbitmq_connection")
    public CachingConnectionFactory connectionFactory(RabbitMqProperties config) {
        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setAddresses(config.getHost());
        //factory.setHost(config.getHost());
        factory.setPort(config.getPort());
        factory.setUsername(config.getUsername());
        factory.setPassword(config.getPassword());
        factory.setVirtualHost(config.getVhost());
        factory.setConnectionTimeout(10000); //设置连接超时时间（单位毫秒）
        //factory.useSslProtocol();

        log.debug("rabbitmq init");
        return factory;
    }

    static public CachingConnectionFactory getConnectionFactory() {
        CachingConnectionFactory factory = (CachingConnectionFactory) XSpringContext.getBean("rabbitmq_connection");
        return factory;
    }


    //@RabbitListener(bindings = @QueueBinding(
    //        value = @Queue("delay_queue"),
    //        exchange = @Exchange("def_exchange")
    //))
    //public void testConsumer(Message message) {
    //    //当队列中有内容是方法会自动执行   推荐Object来接收
    //    //官网推荐Message
    //    byte[] body = message.getBody();//Message将数据存放在body中
    //    String msg = new String(body);
    //    log.debug("test接收到消息: {}", msg);
    //}
}
